package com.malty.mongodb.service;

import com.malty.mongodb.domain.entity.Employee;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class MyMongoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public Employee findById(String id) {
        return mongoTemplate.findById(id, Employee.class);
    }

    public Employee saveOne(Employee employee) {
        mongoTemplate.save(employee);
        return employee;
    }

    public Employee insert(Employee employee) {
        mongoTemplate.insert(employee);
        return employee;
    }

    public List<Object> aggregate() {
        GroupOperation groupOperation = Aggregation.group("gender").first("gender").as("gender").sum("age").as("sum_age").count().as("count");
        ProjectionOperation projectionOperation = Aggregation.project().andInclude("gender", "count", "sum_age");
        SortOperation sortOperation = Aggregation.sort(Sort.Direction.DESC, "sum_age");
        Aggregation aggregation = Aggregation.newAggregation(groupOperation, projectionOperation, sortOperation);
        AggregationResults<Object> company = mongoTemplate.aggregate(aggregation, "company", Object.class);
        return company.getMappedResults();
    }

    public void execute() {
        MongoCollection<Document> collection = mongoTemplate.getCollection("company");
        ListIndexesIterable<Document> documents = collection.listIndexes();
        documents.forEach(e -> log.info(e.toJson()));
    }

    public Boolean removeById(String id) {
        DeleteResult remove = mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)), "company");
        return remove.getDeletedCount() > 0;
    }
}
